/*** 
 * @Date: 2020-07-09 18:10:27
 * @LastEditors: leehave
 * @LastEditTime: 2020-09-09 15:49:37
 */

import wxJS from './wx-sdk.js'
import browser from './browser'
import { Toast } from 'vant'
import { getJssdk } from '@/service/user'
import { isIOS } from '@/utils/index';

const { weiXin } = browser
/**
 * @name 微信初始化sdk
 * @param {array} [jsApiList=[]]
 */
export const initWxJSDK = async(jsApiList = [],openTagList = ['wx-open-launch-weapp'],url) => {
  if (!weiXin) return
  if(url == null || url == undefined){
    url = window.location.href.split('#')[0]
  }
  // const url = window.location.href.split('#')[0]
  // let newurl = url.replace('&','%26')
  /**
   * appid: "wx342181ca0042fa3d"
jsapi_ticket: "kgt8ON7yVITDhtdwci0qeY2I4X-xGNTcR7VxWMEOuSpTJzIp7wHQC6XPwImzYYpA0J6G8thoxWqHU1fOR__o9w"
noncestr: 523560239
signature: "442621032bbf829d052f5564a3259dd7ad8f9794"
timestamp: 1629185157
   */
  const res = await getJssdk(url)
  console.log(res,'getjsdk')
  if(res.status !== 200){
    Toast(res.message)
  }else{
    await wxJS.config({
      appId: res.data.appid, // 必填，公众号的唯一标识
      timestamp: res.data.timestamp, // 必填，生成签名的时间戳
      nonceStr: res.data.noncestr, // 必填，生成签名的随机串
      signature: res.data.signature,// 必填，签名
      jsApiList,
      openTagList
    })
  }
}
/**
 * @name 初始化微信分享
 * @param {object} {title, desc, link, imgUrl}
 */
export const initWxShare = params => {
  wxJS.updateAppMessageShareData(params)
  wxJS.updateTimelineShareData(params)
}

/**
 * @name 微信扫码
 */
export const scanWxQRCode = async callBack => {
  console.log(callBack,'callback')
  const { resultStr } = await wxJS.scanQRCode({
    needResult: 1,
    scanType: ['qrCode']
  })
  console.log('resultStr',resultStr)
  const serial = resultStr.split(',')
  const codeNum = serial[serial.length - 1]
  callBack(codeNum)
}
/**
 * @name 微信支付
 */
export const wxPay = async(payload, callBack) => {
  const { timeStamp: timestamp, ...other } = payload
  await wxJS.chooseWXPay({
    ...other,
    timestamp
  })
  callBack()
}
/**
 * @name 微信图片预览
 */
export const previewImage = (urls, index = 0) => {
  wxJS.previewImage({
    current: urls[index], // 当前显示图片的http链接
    urls // 需要预览的图片http链接列表
  })
}
